<?php namespace Summer\Hjd\Widgets;

use RainLab\User\Models\User as UserModel;
use Str;
use Backend\Classes\WidgetBase;
use Summer\Hjd\Classes\CommonApi;
use Summer\Hjd\Models\CorrectionModel;
use Input;
use Flash;
use Validator;
use ValidationException;

/**
 * 资金校正
 */
class Correction extends WidgetBase
{
    protected $correctionFormWidget;
    public function __construct($controller, $alias)
    {
        $this->alias = $alias;
        parent::__construct($controller, []);
        $this->bindToController();
        if ($this->correctionFormWidget = $this->makeCorrectionFormWidget()) {
            $this->correctionFormWidget->bindToController();
        }
    }

    /**
     * Renders the widget.
     * @return string
     */
    public function render()
    {

        return $this->makePartial('body', ['correctionFormWidget'=>$this->correctionFormWidget]);

    }

    protected function makeCorrectionFormWidget()
    {
        $widgetConfig = $this->makeConfig('~/plugins/summer/hjd/models/correctionmodel/fields.yaml');
        $widgetConfig->model = new CorrectionModel();
        $widgetConfig->alias = 'correctionForm';

        $widget = $this->makeWidget('Backend\Widgets\Form', $widgetConfig);

        $widget->bindEvent('form.beforeRefresh', function ($holder) {
            $holder->data = [];
        });

        return $widget;
    }
    /**
     * 资金校正提交
     */
    public function onCorrection()
    {
        $pdata=Input::all();
        $rules=[
            'target' => 'required',
            'money' => 'required|numeric|positive',
            'currency_slug' => 'required',
            'inout' => 'required'
        ];
        $messages=[
            'target.required'=>'请选择校正用户',
            'money.required'=>'请输入校正金额',
            'money.numeric'=>'校正金额格式错误',
            'money.positive'=>'校正金额必须是正数',
            'currency_slug.required'=>'请选择校正币种',
            'inout.required'=>'请选择校正类型,增加或扣除',
        ];
        $validator = Validator::make($pdata, $rules, $messages);
        if ($validator->fails()) {
            throw new ValidationException($validator);
        }
        $user_id=$pdata['target'];
        $money=$pdata['money'];
        $currency_slug=$pdata['currency_slug'];
        $inout=$pdata['inout'];
        $comment=$pdata['comment'];
        $userinfo=UserModel::where('id',$user_id)->first();
        if(!$userinfo){
            Flash::error('该会员不存在');
            return;
        }
        if($inout==1){
            $change_slug='admin_add';//后台充值
        }else{
            $change_slug='admin_red';//后台扣除
        }
        $common_api=new CommonApi();
        $res=$common_api->settleDetailed($userinfo->id,0,$money,$inout,$currency_slug,[
            'change_slug'=>$change_slug,
            'comment'=>$comment,
        ]);
        Flash::success('操作成功');
        return;
    }

}
